<script setup lang="ts">
import {
  DeleteOutlined,
  FormOutlined,
  PlusOutlined,
  SyncOutlined,
} from '@ant-design/icons-vue'
import type { TableProps } from 'ant-design-vue'
import { CommTableSize } from '~/components/comm-table/comm-table-data.ts'

import { enabledApiStateByIdApi, queryApiListByMenuIdApi, removeApiByIdApi } from '~/api/setting/api.ts'
import type { ApiReq, ApiResp } from '~/api/setting/model/api.ts'
import { ApiTableColumns } from '~/pages/setting/datas/menu-data.ts'
import type { MenuResp } from '~/api/setting/model/menu.ts'
import MenuApiEditModal from '~/pages/setting/components/menu-api-edit-modal.vue'

const props = defineProps({
  menuData: Object,
})

defineExpose({
  refreshData(selected, node) {
    refreshListData(selected, node)
  },
})

const message = useMessage()

const tableSize = shallowRef<string[]>(CommTableSize)

const columns = ApiTableColumns
const loading = shallowRef(false)

const dataSource = shallowRef<ApiResp[]>([])

const formQuery = reactive<ApiReq>({
  apiTitleByLike: undefined,
})

const menuResp = shallowRef<MenuResp>({})

const loadingOfSwitch = shallowRef(false)

const open = ref(false)
const optType = ref('create')
const apiResp = ref<ApiResp>({})

async function init() {
  if (loading.value) {
    return
  }
  loading.value = true
  try {
    const apiReq: ApiReq = {
      menuId: menuResp.value.id,
      apiTitleByLike: formQuery.apiTitleByLike,
    }
    dataSource.value = await queryApiListByMenuIdApi(apiReq)
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }
}

async function onSearch() {
  await init()
}

/**
 * 刷新数据
 */
async function refreshListData(selected, node: MenuResp) {
  if (selected) {
    menuResp.value = node
    await init()
  } else {
    dataSource.value = []
  }
}

/**
 * 状态开启或关闭
 */
async function onSwitchChange(item: ApiResp) {
  loadingOfSwitch.value = true
  const apiReq: ApiReq = {
    id: item.id,
  }
  const result = await enabledApiStateByIdApi(apiReq)
  if (result) {
    loadingOfSwitch.value = false
    await init()
  }
}

function openModalEditApi(opt: string, item?: ApiResp) {
  open.value = true

  optType.value = opt
  if (opt === 'create') {
    apiResp.value = {}
  } else {
    apiResp.value = item || {}
  }
}

/**
 * 删除功能
 *
 * @param item
 */
async function onDeleteApi(item: ApiResp) {
  const close = message.loading('删除中......')
  try {
    const apiReq: ApiReq = {
      id: item.id,
    }
    const isDel = await removeApiByIdApi(apiReq)
    if (isDel) {
      await init()
    }
    message.success('删除成功')
  } catch (e) {
    console.log(e)
  } finally {
    close()
  }
}

async function onSaveSuccess() {
  open.value = false
  await onSearch()
}

onMounted(() => {
  if (props?.menuData) {
    menuResp.value = props?.menuData
    init()
  }
})
</script>

<template>
  <div>
    <a-row>
      <a-col :span="8">
        <a-input-search
          v-model:value="formQuery.apiTitleByLike"
          placeholder="请输入接口名称"
          enter-button="搜索"
          class="input-search"
          @search="onSearch"
        />
      </a-col>
      <a-col :span="8" :offset="8" style="text-align: right">
        <a-button v-if="menuResp.type === 1" type="primary" @click="openModalEditApi('create')">
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
      </a-col>
    </a-row>

    <a-table
      :loading="loading"
      row-key="id"
      :columns="columns"
      :data-source="dataSource"
      :size="tableSize[0] as TableProps['size']"
    >
      <template #bodyCell="scope">
        <template v-if="scope?.column?.dataIndex === 'indexNo'">
          {{ scope?.index + 1 }}
        </template>
        <template v-if="scope?.column?.dataIndex === 'apiTitle'">
          <a-tag :color="scope?.record?.stateId === 1 ? 'green' : 'red'">
            {{ scope?.record?.stateId === 1 ? '有效' : '无效' }}
          </a-tag>
          <a-tooltip placement="topLeft" :title="scope?.record?.apiTitle">
            {{ scope?.record?.apiTitle }}
          </a-tooltip>
        </template>
        <template v-if="scope?.column?.dataIndex === 'apiUrl'">
          <a-tag class="processing-tag" color="processing">
            <template #icon>
              <SyncOutlined :spin="true" />
            </template>
            {{ scope?.record?.apiHttpMethod }}
          </a-tag>
          <a-tooltip placement="topLeft" :title="scope?.record?.apiUrl">
            {{ scope?.record?.apiUrl }}
          </a-tooltip>
        </template>
        <template v-if="scope?.column?.dataIndex === 'stateId'">
          <a-switch
            :checked="(scope?.record?.stateId)"
            :loading="loadingOfSwitch"
            checked-children="有效"
            un-checked-children="无效"
            :checked-value="1"
            :un-checked-value="0"
            @change="onSwitchChange(scope?.record)"
          />
        </template>
        <template v-if="scope?.column?.dataIndex === 'action'">
          <div>
            <span>
              <a><FormOutlined @click="openModalEditApi('edit', scope?.record)" /></a>
              <a-divider type="vertical" />
              <a-popconfirm
                v-if="dataSource.length"
                title="确认删除?"
                @confirm="onDeleteApi(scope?.record)"
              >
                <a><DeleteOutlined /></a>
              </a-popconfirm>
            </span>
          </div>
        </template>
      </template>
    </a-table>
    <MenuApiEditModal
      v-if="open"
      v-model:open="open"
      :opt-type="optType"
      :api-data="apiResp"
      :menu-id="menuResp.id"
      @on-save-success="onSaveSuccess"
    />
  </div>
</template>

<style scoped lang="less">
  .component-card {
    min-height: 480px;
  }
  .input-search {
    margin-bottom: 16px;
    width: 300px;
  }
  .processing-tag {
    width: 72px;
  }
</style>
